﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Net;

using Google.GData.Documents;
using Google.GData.Client;
using Google.Contacts;
using Google.Documents;
using Google.GData.AccessControl;
using Google.GData.Extensions;

using System.Collections.Specialized; 

using Excel = Microsoft.Office.Interop.Excel; 

using LicenseManager; 

namespace ContentMakerResearch
{
    
    class Program
    {

        private WebRequest MakeWebRequest(string target) {
            WebRequest request = WebRequest.Create(target);
            return request; 
        }

        private void TestMergingExcel()
        {
            
        }

        //private void AddHeaders(
        public void TestContentAnalyze()
        {
            RequestSettings m_Settings;
            DocumentsService m_Service;


            GDataGAuthRequestFactory authFactory = new GDataGAuthRequestFactory("writely", "UpriseApps-OfficeInCloud-v1");
            authFactory.AccountType = "HOSTED";
            m_Service = new DocumentsService(authFactory.ApplicationName);
            m_Service.Credentials = new GDataCredentials("andrey.kandzuba", "mamamilaramu");

            try
            {
                m_Service.QueryAuthenticationToken(); // Authenticate the user immediately
            }
            catch (ArithmeticException e)
            {
                System.Console.WriteLine(e.Message);
                return;
            }

            m_Settings = new RequestSettings("OfficeInCloud", m_Service.Credentials);
            m_Settings.AutoPaging = true;
            m_Settings.PageSize = 100;

            DocumentsRequest m_request = new DocumentsRequest(m_Settings);

            Assembly currentAssembly = Assembly.GetExecutingAssembly();
            //currentAssembly.
            string outputPath = Path.Combine(Path.GetDirectoryName(currentAssembly.Location), "test_article.doc");
            FileStream fStream = new FileStream(outputPath, FileMode.OpenOrCreate);
            fStream.Write(Properties.Resources.test_artical, 0, Properties.Resources.test_artical.Length);

           
            DocumentEntry n = null;
            try
            {

                n = m_Service.UploadDocument(outputPath, "test artical.doc");

                String ContentURL = n.Content.Src.Content;

                WebRequest w_request = MakeWebRequest(ContentURL);
                w_request.ContentType = n.Content.Type;
                w_request.Credentials = m_Settings.Credentials.NetworkCredential;
                WebResponse w_response = w_request.GetResponse();

                Stream m_stream = w_response.GetResponseStream();
                
            }
            catch (Exception ex)
            {
                System.Console.Write(ex.Message);
            }
            finally
            {
                if (n != null)
                    m_Service.Delete(n);

            }

        }

        public void TestUploadUpdateDelete()
        {
            RequestSettings m_Settings;
            DocumentsService m_Service;



            GDataGAuthRequestFactory authFactory = new GDataGAuthRequestFactory("writely", "UpriseApps-OfficeInCloud-v1");
            authFactory.AccountType = "HOSTED";
            m_Service = new DocumentsService(authFactory.ApplicationName);
            m_Service.Credentials = new GDataCredentials("andrey.kandzuba", "mamamilaramu");

            m_Settings = new RequestSettings("OfficeInCloud", m_Service.Credentials);
            m_Settings.AutoPaging = true;
            m_Settings.PageSize = 100;


            try
            {
                m_Service.QueryAuthenticationToken(); // Authenticate the user immediately
            }
            catch (ArithmeticException e)
            {
                System.Console.WriteLine(e.Message);
            }

            if (m_Service != null)
            {
                DocumentsRequest m_request = new DocumentsRequest(m_Settings);

                Assembly currentAssembly = Assembly.GetExecutingAssembly();
                //currentAssembly.
                string outputPath = Path.Combine(Path.GetDirectoryName(currentAssembly.Location), "test_article.doc");
                FileStream fStream = new FileStream(outputPath, FileMode.OpenOrCreate);
                fStream.Write(Properties.Resources.test_artical, 0, Properties.Resources.test_artical.Length);

                string outputPath2 = Path.Combine(Path.GetDirectoryName(currentAssembly.Location), "test_article_2.doc");
                FileStream fStream2 = new FileStream(outputPath2, FileMode.OpenOrCreate);
                fStream2.Write(Properties.Resources.test_artical_2, 0, Properties.Resources.test_artical_2.Length);
                fStream2.Close();

                fStream2 = new FileStream(outputPath2, FileMode.Open);


                DocumentEntry n = null;
                AtomEntry an = null;
                try
                {

                    n = m_Service.UploadDocument(outputPath, "test artical.doc");
                    n.Summary.Text = "Microsoft Oracle UpriseApps";



                    Uri postUri = new Uri(n.MediaUri.Content);
                    GDataLoggingRequestFactory factory = new GDataLoggingRequestFactory(DocumentsService.GDocumentsService, "DocListUploader");
                    factory.MethodOverride = true;
                    m_Service.RequestFactory = factory;
                    // this one is necessary for Put request
                    factory.CustomHeaders.Add(GDataRequestFactory.IfMatch + ":*");


                    an = m_Service.Update(postUri, fStream2, "application/msword", n.Title.Text); //n.Etag.ToString()); 

                    factory.MethodOverride = false;

                }
                catch (GDataRequestException ex)
                {
                    System.Console.Write(ex.Message);
                }
                finally
                {
                    if (an != null)
                        m_Service.Delete(an);

                }


            }
        }
        

            public void TestACLOptions()
        {
            RequestSettings m_Settings;
            DocumentsService m_Service;



            GDataGAuthRequestFactory authFactory = new GDataGAuthRequestFactory("writely", "UpriseApps-OfficeInCloud-v1");
            authFactory.AccountType = "HOSTED";
            m_Service = new DocumentsService(authFactory.ApplicationName);
            m_Service.Credentials = new GDataCredentials("andrey.kandzuba", "mamamilaramu");

            m_Settings = new RequestSettings("OfficeInCloud", m_Service.Credentials);
            m_Settings.AutoPaging = true;
            m_Settings.PageSize = 100;


            try
            {
                m_Service.QueryAuthenticationToken(); // Authenticate the user immediately
            }
            catch (ArithmeticException e)
            {
                System.Console.WriteLine(e.Message);
            }

            if (m_Service != null)
            {
                DocumentsRequest m_request = new DocumentsRequest(m_Settings);

                Assembly currentAssembly = Assembly.GetExecutingAssembly();
                //currentAssembly.
                string outputPath = Path.Combine(Path.GetDirectoryName(currentAssembly.Location), "test_article.doc");
                FileStream fStream = new FileStream(outputPath, FileMode.OpenOrCreate);
                fStream.Write(Properties.Resources.test_artical, 0, Properties.Resources.test_artical.Length);

             
                DocumentEntry n = null;
                AtomEntry an = null;
                try
                {
                    //GDataLoggingRequestFactory factory = new GDataLoggingRequestFactory(DocumentsService.GDocumentsService, "DocListUploader");
                    //factory.MethodOverride = true;
                    //m_Service.RequestFactory = factory;
                    // this one is necessary for Put request
                    //factory.CustomHeaders.Add(GDataRequestFactory.IfMatch + ":*");


                    n = m_Service.UploadDocument(outputPath, "test artical.doc");
                 
   
                    DocumentsFeed docsFeed = null;
                    
                    docsFeed = (DocumentsFeed)m_Service.Query(new AclQuery(n.AccessControlList));
                    
                    // Add new shared user
                    AclFeed aclF = new AclFeed(new Uri("http://schemas.google.com/g/2005#batch"), m_Service);
                    AclEntry new_entry = new AclEntry();

                    new_entry.Role = new AclRole("reader");
                    new_entry.Scope = new AclScope();
                    new_entry.Scope.Value = "john.jsmith.smith90@gmail.com";
                    new_entry.Scope.Type = "user";
                    //"john.jsmith.smith90@gmail.com", "user");
                    new_entry.BatchData = new GDataBatchEntryData(GDataBatchOperationType.insert);
                    new_entry.Id = new AtomId(n.AccessControlList + "/user%3A" + new_entry.Scope.Value);
                   
                    aclF.Categories.Add(new AtomCategory("http://schemas.google.com/acl/2007#accessRule",
                                                        "http://schemas.google.com/g/2005#kind"));
                    aclF.Entries.Add(new_entry);
                    

                    Uri aclUri = new Uri(n.AccessControlList + "/batch");
                    
                    outputPath = Path.Combine(Path.GetDirectoryName(currentAssembly.Location), "request.xml");
                    fStream = new FileStream(outputPath, FileMode.Create);
                    aclF.SaveToXml(fStream);
                    fStream.Close();


                    AtomFeed response = m_Service.Batch(aclF, aclUri);

                    outputPath = Path.Combine(Path.GetDirectoryName(currentAssembly.Location), "response.xml");
                    fStream = new FileStream(outputPath, FileMode.Create);
                    response.SaveToXml(fStream);
                    fStream.Close();

                    // Delete previously added user
                    aclF = new AclFeed(new Uri("http://schemas.google.com/g/2005#batch"), m_Service);
                    new_entry = new AclEntry();

                    new_entry.Role = new AclRole("reader");
                    new_entry.Scope = new AclScope();
                    new_entry.Scope.Value = "john.jsmith.smith90@gmail.com";
                    new_entry.Scope.Type = "user";
                    //"john.jsmith.smith90@gmail.com", "user");
                    new_entry.BatchData = new GDataBatchEntryData(GDataBatchOperationType.delete);
                    new_entry.Id = new AtomId(n.AccessControlList + "/user%3A" + new_entry.Scope.Value);

                    aclF.Categories.Add(new AtomCategory("http://schemas.google.com/acl/2007#accessRule",
                                                        "http://schemas.google.com/g/2005#kind"));
                    aclF.Entries.Add(new_entry);
                    

                    aclUri = new Uri(n.AccessControlList + "/batch");

                    outputPath = Path.Combine(Path.GetDirectoryName(currentAssembly.Location), "request.xml");
                    fStream = new FileStream(outputPath, FileMode.Create);
                    aclF.SaveToXml(fStream);
                    fStream.Close();


                    response = m_Service.Batch(aclF, aclUri);

                    outputPath = Path.Combine(Path.GetDirectoryName(currentAssembly.Location), "response.xml");
                    fStream = new FileStream(outputPath, FileMode.Create);
                    response.SaveToXml(fStream);
                    fStream.Close();


                    //factory.MethodOverride = false;
                }
                catch (GDataRequestException ex)
                {
                    System.Console.Write(ex.Message);
                }
                finally
                {
                    if (n != null)
                        m_Service.Delete(n);

                }


            }
        
        }

        private void TestZohoLogin()
        {
            ZohoLicenseManager m_LicenceManager = new ZohoLicenseManager("info@upriseapps.com", "mamamilaramu");

            ZohoTypes.ZohoContact contact1 = null;
            ZohoTypes.ZohoContact contact2 = null;
            ZohoTypes.ZohoContact contact3 = null;
            ZohoTypes.ZohoContact contact4 = null; 
            try
            {
                 m_LicenceManager.Login();
                 //work with Zoho here
                 contact1 = m_LicenceManager.SearchForContact("volodymyr.obrizan@dnt-lab.com");
                 contact2 = m_LicenceManager.SearchForContact("aaa@aaa.com");
                 contact3 = m_LicenceManager.SearchForContact("andrey.kandzuba@gmail.com");

                 contact3.LastLogin = DateTime.Now;
                 m_LicenceManager.UpdateContact(contact3);

                 contact4 = new ZohoTypes.ZohoContact();
                 contact4.FirtsName = "TestFirstName";
                 contact4.LastName = "TestLastName";
                 contact4.Email = "testmail@gmail.com";
                 contact4.Phone = "5555555555";
                 contact4.LastLogin = DateTime.Now;

                 m_LicenceManager.InsertContact(contact4);

                 Console.Write("New Contact ID = " + contact4.ID);

                 m_LicenceManager.Logout();
            }
            catch (ZohoAuthorizationException ex)
            {
                System.Console.Write(ex.Message); 
            }
            
        }

        private void TestMergeWorkBooks()
        {
            Assembly currentAssembly = Assembly.GetExecutingAssembly();
            //currentAssembly.
            string outputPath = Path.Combine(Path.GetDirectoryName(currentAssembly.Location), "Original.xlsx");
            FileStream fStream = new FileStream(outputPath, FileMode.OpenOrCreate);
            fStream.Write(Properties.Resources.Original, 0, Properties.Resources.Original.Length);

            string outputPath2 = Path.Combine(Path.GetDirectoryName(currentAssembly.Location), "Update.xlsx");
            FileStream fStream2 = new FileStream(outputPath2, FileMode.OpenOrCreate);
            fStream2.Write(Properties.Resources.Update, 0, Properties.Resources.Update.Length);
            fStream2.Close();

            //Excel._Application m_app = Excel.  

        
        }


        private void UploadFilesToRemoteUrl(string url, 
                                           string[] files, 
                                           string logpath, 
                                           NameValueCollection nvc)
        {    
    
            string boundary = "----------------------------" +    DateTime.Now.Ticks.ToString("x");      
            HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);    
            httpWebRequest2.ContentType = "multipart/form-data; boundary=" +    boundary;    
            httpWebRequest2.Method = "POST";    
            httpWebRequest2.KeepAlive = true;    
            httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;
            httpWebRequest2.Referer = "http://docs.google.com/DocAction?action=updoc&hl=en";

            //NameValueCollection nv1 = new NameValueCollection();
            //nv1.Add("Host", "docs.google.com");
            //httpWebRequest2.Headers.Add(nv1);
            
            httpWebRequest2.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/x-icq, application/x-silverlight, application/x-silverlight-2-b2, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, */*";
            
            NameValueCollection nv2 = new NameValueCollection();
            nv2.Add("Accept-Language", "en-us");
            httpWebRequest2.Headers.Add(nv2);



            Stream memStream = new System.IO.MemoryStream();    
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +    boundary + "\r\n");
            string formdataTemplate = "\r\n--" + boundary +    "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";    
            
            foreach (string key in nvc.Keys)    
            {        
                string formitem = string.Format(formdataTemplate, key, nvc[key]);        
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);        
                memStream.Write(formitembytes, 0, formitembytes.Length);    
            }    
            memStream.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\r\n\r\n";    
            
            for (int i = 0; i < files.Length; i++)    
            {        
                //string header = string.Format(headerTemplate, "file" + i, files[i]);        
                string header = string.Format(headerTemplate, "uplTheFile", files[i]);        
                byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);        
                memStream.Write(headerbytes, 0, headerbytes.Length);        
                FileStream fileStream = new FileStream(files[i], FileMode.Open,        FileAccess.Read);        
                byte[] buffer = new byte[1024];        
                int bytesRead = 0;        
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)        
                {            
                    memStream.Write(buffer, 0, bytesRead);        
                }        
                memStream.Write(boundarybytes, 0, boundarybytes.Length);        
                fileStream.Close();    
            }    

            httpWebRequest2.ContentLength = memStream.Length;    
            Stream requestStream = httpWebRequest2.GetRequestStream();

           
            memStream.Position = 0;   
            byte[] tempBuffer = new byte[memStream.Length];    
            memStream.Read(tempBuffer, 0, tempBuffer.Length);    
            memStream.Close();

            FileStream fs = new FileStream("C:\\post.txt", FileMode.Create); 
            fs.Write(tempBuffer, 0, tempBuffer.Length);
            fs.Close();
            

            //Console.Write(Encoding.UTF8.GetString(tempBuffer));

            requestStream.Write(tempBuffer, 0, tempBuffer.Length);    
            requestStream.Close();    
            

            WebResponse webResponse2 = httpWebRequest2.GetResponse();    
            Stream stream2 = webResponse2.GetResponseStream();    
            StreamReader reader2 = new StreamReader(stream2);

            Console.Write(reader2.ReadToEnd());

            webResponse2.Close();    
            httpWebRequest2 = null;    
            webResponse2 = null;

        }


        public void TestUploadViaWebUI()
        {
            RequestSettings m_Settings;
            DocumentsService m_Service;



            GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("writely", "UpriseApps-OfficeInCloud-v1");
            authFactory.AccountType = "HOSTED";
           
            m_Service = new DocumentsService(authFactory.ApplicationName);
            m_Service.Credentials = new GDataCredentials("andrey.kandzuba", "mamamilaramu");

            m_Settings = new RequestSettings("OfficeInCloud", m_Service.Credentials);
            m_Settings.AutoPaging = true;
            m_Settings.PageSize = 100;
            string m_SecurityToken = "";


            try
            {
                m_SecurityToken = m_Service.QueryAuthenticationToken(); // Authenticate the user immediately
                
            }
            catch (ArithmeticException e)
            {
                System.Console.WriteLine(e.Message);
                return; 
            }

            //String singleUseToken = m.QueryString["token"];

            if (m_Service != null)
            {
                DocumentsRequest m_request = new DocumentsRequest(m_Settings);

                Assembly currentAssembly = Assembly.GetExecutingAssembly();
                //currentAssembly.
                string outputPath = Path.Combine(Path.GetDirectoryName(currentAssembly.Location), "Original.xlsx");
                FileStream fStream = new FileStream(outputPath, FileMode.OpenOrCreate);
                fStream.Write(Properties.Resources.Original, 0, Properties.Resources.Original.Length);
                fStream.Close(); 

                try
                {


                    string[] files = new string[1];
                    files[0] = "Original.xlsx";
                    NameValueCollection form = new NameValueCollection();
                    form.Add("security_token", m_SecurityToken);
                    form.Add("formsubmitted", "true");
                    form.Add("uploadURL", "");
                    form.Add("DocName", "");
                    form.Add("saveChanges", "Upload File"); 

                    UploadFilesToRemoteUrl("http://docs.google.com/DocAction?action=updoc",
                                            files,
                                            null,
                                            form);


                }
                catch (WebException ex)
                {
                    Console.WriteLine(ex.ToString());
                    if (ex.Status == WebExceptionStatus.ConnectFailure)
                    {
                        Console.WriteLine("Are you behind a firewall?  If so, go through the proxy server.");
                    }

                }
                catch (GDataRequestException ex)
                {
                    System.Console.Write(ex.Message);
                }
                
            }
 
        }
 

 
        static void Main(string[] args)
        {
            ContentMakerResearch.Program program = new Program();
            //program.TestContentAnalyze();
            //program.TestACLOptions(); 
            program.TestUploadViaWebUI(); 
        }
    }
}

